<?php
/**
 *   +----------------------------------------------------------------------
 *   | Author: ONLY <491518132@qq.com>
 *	+----------------------------------------------------------------------
 *   | Creater Time : 2013-5-7
 *   +----------------------------------------------------------------------
 *   | Link (http://www.cloudsskill.com http://www.goshopx.com  http://www.shopingj.com )
 *   +----------------------------------------------------------------------
 **/
// +----------------------------------------------------------------------
// | 布局标签类
// +----------------------------------------------------------------------
// | Author: hwf
// +----------------------------------------------------------------------

/**
 * 布局标签类
 * 
 * 目前主要用于O2O端页面标签显示
 */
class Layout {
	
	private $dao,$layout,$tags_obj,$tags,$ads,$tree;
	private $layout_config;
	
	function __construct( $model='Layout' ){
		$this->dao = M( model );
		$this->layout = M('Layout');
		$this->tags = M('Tags');
		$this->tags_obj = M('TagsObj');
		$this->ads = M('Ads');
		$this->tree = array();
	}
	
	/**
	 * 添加操作
	 * 包括添加布局、添加标签、添加标签内容
	 * @param array $map 要添加的数据
	 * @return array 
	 */
	function add($map,$model=''){
		if ( $model == 'tags' ) {
			// 添加标签时
			if ( !$map['name'] && !$map['user_id'] ){return false;}
			$this->_updata($map, $this->tags);
			
		}elseif ( $model == 'product' ) {
			// 添加标签内容：产品时
			if ( !$map['tags_id'] && !$map['product_id'] )	{return false;}
			$this->_updata($_POST, $this->tags_obj);
		}else	{
			if ( !$map['layout'] && !$map['cell_id'] && !$map['user_id'] ){
			// 添加布局时
				return false;
			}
			$this->_updata($_POST, $this->layout);
		}
	}

	/**
	 * 
	 * @param unknown_type $_uid
	 * @param unknown_type $_type
	 * @param unknown_type $_tagname
	 */
	function initags($_uid,$_type,$_tagname){
		$model = M('Tags');
		$where = array();
		$where['type'] = $_type;
		$where['user_id'] = $_uid;
		$id = $model->field('id')->where($where)->select();
		if(! $id){
			$data = array();
			$data['user_id'] = $_uid;
			$data['parent_id'] = $data['path'] = '0';
			$data['type'] = $_type;
			$temp = array();
			$temp['user_id'] = $_uid;
			$temp['type'] = '1';
			$temp['status'] = '1';
			foreach ($_tagname as $k => $v){
				$data['name'] = $v;
				$reid = $this->updata($data, "Tags");
				$temp['layout'] = $k;
				$temp['cell_id'] = $reid;
				$reid = $this->updata($temp, 'Layout');
			}
		}
	}
	
	/**
	 * 数据表的写入与更新
	 * @param array $_POST
	 * @param 表模型 $_mode
	 * @return message
	 */
		function updata ($_data,$_model) {
			$model = M($_model);
			if($model){
				if($_data){
					$reid = $model->create($_data);
					if($reid){
						if($_data['id']){
							$reid = $model->save();
							return $reid;
						}else{
							$reid = $model->add();
							return $reid;
						}
					}else{
						return false;
					}
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		
	
	/**
	 * 返回提示信息
	 * @param multitype $_val
	 * @param json
	 */
	function _message($_val,$_line,$_msg){
		if(!$_val || empty($_val) || $_val === 'false'){
			$mesg=array("status"=>0,'msg'=>$_msg.'在'.$_line.'行');
			exit(json_encode($mesg));
		}else{
			$mesg=array("status"=>1,'msg'=>$_msg);
			exit(json_encode($mesg));
		}
	}
	/**
	 * 删除操作
	 * 包括删除布局、删除标签、删除标签内容
	 * @param array $map 删除的数据，可以默认只支持根据ID来删除
	 * @return array 
	 */
	function delete($_ids,$model=''){
		$where['id'] = is_array($_ids) ? array('IN',implode(',',$_ids)) : $_ids;
		$reid = $model->where($where)->delete();
		if($reid){
			$this->_message(true, __LINE__, '删除成功！');
		}else{
			$this->_message('', __LINE__, '删除失败！');
		}
	}

	/**
	 * 编辑操作
	 * 包括编辑布局、编辑标签、编辑标签内容
	 * @param array $map 编辑的数据
	 * @return array $reinfo
	 */
	function edit($_id = false,$model = false){
		if($_id && $model){
			$where['id'] = $_id;
			$reinfo = $model->where($where)->select();
			//$this->assign('reinfo',$reinfo);
			return $reinfo;
		}else{
			return false;
		}
		//$this->display();		
	}
	
	/**
	 * 获取编辑内容 
	 * @param int|array $ids 标签IDs
	 * @return array 产品或文章IDs
	 */
	function get_obj($ids){
		$map = array();
		if ( is_array($ids) ) $map['id'] = array('in', $ids);
		else $map['id'] = $ids;
		$obj_arr = $this->tags_obj->field( 'obj_id' )->where( $map )->select();
		return $obj_arr;
	}
	
	/**
	 * 获取某个页面的布局
	 * @param string $_action 页面 
	 * @param id $_uid 用户ID
	 * @return array
	 */
	function get_cell($_action,$_uid){
		$_uid ? true : $this->_message('', __LINE__, '请传入用户名！');
		$postion = $_action ? $_action : 'index';
		
		$mode = M('');
		$cells = $mode->query( "select *,GROUP_CONCAT(cell_id order by sequence desc) AS cells 
				from layout where user_id={$_uid} and layout like '$postion-%' group by layout" );
		
		return $cells;
		
		
	}
	
	/**
	 * 返回用户下的标签
	 * @param string $_uid
	 * @return array $tag
	 */
	function tags($_uid,$_field = 'id,name,parent_id',$map=array()){
		$where = array('user_id'=>$_uid);
		if ( $map ) $where = array_merge($map,$where);
		$tag = $this->tags->field($_field)->where($where)->order('parent_id,sequence')->select();
		$tag = $this->_taglevel($tag);
		$this->tree = array();
		return $tag;
	}
	
	/**
	 * 返回标签信息
	 * @param id $_tagid
	 * @return array $taginfo
	 */
	function taginfo($_tagid){
		$where['id'] = is_array($_tagid) ? array('IN',implode(',', $_tagid)) : $_tagid;
		$temp = $this->tags->where($where)->select();
		$taginfo = array();
		foreach ($temp as $k => $v){
			$taginfo[$v['id']] = $v;
		}
		return $taginfo;
	}
	
	/**
	 * 检查产品是否存在标签下面
	 * @param $proids 产品id
	 * @param $userid 商户Id ，用户id
	 * @return array $proids
	 */
	function chektagpro($proids,$userid){
		$map['t.user_id'] = $userid;
		$map['obj_id'] = is_array($proids)?array('in',implode(',', $proids)):$proids;
		$res = $this->tags_obj->join(' tags as t on t.id = tags_obj.tags_id')->where($map)->select();
		if($res){
			foreach ($res as $vo){
				$res_proids[] = $vo['obj_id'];
			}
			return array_diff($proids, $res_proids);
		}else{
			if(is_array($proids)){
				return $proids;
			}else{
				return array($proids);
			}
			
		}
	}
	
	/**
	 * 删除标签里的产品
	 * @param int|array $_proids
	 * @param int|string $_uid
	 */
	function delproinfo($_proids, $_uid){
		if($_proids){
			$where = array();
			$where['product_id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
			$where['user_id'] = $_uid;
			//删除product_o2o表中 商品信息
			$model = M('ProductO2o');
			$model -> where($where)->delete();
			//删除product_price_o2o 表 价格信息
			$model = M('ProductPriceO2o');
			$model -> where($where)->delete();
			//删除product_des_o2o 表 商品详情信息
			$model = M('ProductDesO2o');
			$model -> where($where)->delete();
			return 1;
		}
	}
	
	/**
	 *  删除标签
	 * @param int|string $_tagid
	 * @param int|string $_uid
	 */
	function deltag($_tagid,$_uid){
		$proids = $this->tagtopro($_tagid, $_uid);
		$this->delproinfo($proids, $_uid);
		$this->tags->where(array('id'=>$_tagid))->delete();
		$this->tags_obj->where(array('tags_id'=>$_tagid))->delete();
		$reid = $this->layout->where(array('user_id'=>$_uid,'cell_id'=>$_tagid))->delete();
		return $reid;
	}
	
	/**
	 * 返回层次关系
	 * @param array $_tags
	 * @param int $_pid
	 * @param int $_level
	 * @return array $this->tree
	 */
	function _taglevel ($_tags,$_pid = 0,$_level = 1) {
		foreach ($_tags as $k => $v){
			if($v['parent_id'] == $_pid){
				$v['level'] = $_level;
				$this->tree[$v['id']] = $v;
				$this->_taglevel($_tags, $v['id'],$_level+1);
			}
		}
		return $this->tree;
	}
	
	/**
	 * 返回树形菜单
	 * @param array $_cate
	 * @return array $_cate
	 */
	function catelevel ($_cate,$_level = 3) {
		foreach ($_cate as $k => &$v){
			$stra = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|';
			$strb = '&nbsp;--&nbsp;';
			$strc = '';

			if($v['level'] < $_level){

				for($i=0;$i<$v['level'];$i++){
					$strc = $strc.$stra;
				}
				$v['name'] = $strc.$strb.$v['name'];
			}else{
				unset($_cate[$k]);
			}
		}
		return $_cate;
	}
	
	/**
	 * 返回树形结构
	 * @param array $_tags
	 * @param array $_pid
	 * @param array $_level
	 * @return array $this->tree
	 */
	function tagtree ($_tags,$_pid = 0) {
		$temp = array();
		foreach ($_tags as $k => &$v){
			if($v['parent_id'] == $_pid){
				$temp[$v['id']] = $v;
				$temp[$v['id']]['children'] = $this->tagtree($_tags, $v['id']);
			}
		}
		return $temp;
	}
	
	/**
	 * 返回标签下树形的子标签
	 * @param array $_tag
	 * @param int $_tagid
	 * @return array $children
	 */
	function tagtochildren($_tag ,$_tagid = '0'){
		$children = array();
		foreach ($_tag as $k => $v){
			if($v['parent_id'] == $_tagid){
				$children[$k] = $v;
				$this->tree = array();
				unset($_tag[$k]);
				$children[$k]['children'] = $this->tagtree($_tag, $v['id']);
			}
		}
		return $children;
	}
	
	/**
	 * 返回标签子分类
	 * @param array $_tags
	 * @param array $_pid
	 * @param array $_level
	 * @return array $this->tree
	 */
	function tagtozi ($_tags,$_pid = 0,$_level = 1) {
		foreach ($_tags as $k => $v){
			if($v['parent_id'] == $_pid){
				$v['level'] = $_level;
				$this->tree[$v['id']] = $v;
				$this->tagtozi($_tags, $v['id'],$_level+1);
			}
		}
		return $this->tree;
	}
	
	/**
	 * 返回标签下的产品
	 * @param array $_ids
	 * @return array $proids
	 */
	function tagtopro ($_ids,$_uid,$_status=TRUE,$_limit = FALSE) {
		$model = M();
		$where = "";
		$where .= is_array($_ids) ? "t.tags_id IN (".implode(',', $_ids).")" : "t.tags_id=".$_ids;
		$status = $_status ? 'AND o.`status`=1 AND p.`status`=1 AND p.price >1 ' : " AND p.`status`=1";
		$_limit = $_limit ? " LIMIT $_limit" : '';
		$sql = "SELECT p.id FROM tags_obj as t LEFT JOIN product_o2o as o ON t.obj_id=o.product_id LEFT JOIN product as p ON t.obj_id=p.id WHERE $where  AND o.user_id=".$_uid." $status ORDER BY t.sequence DESC,t.id DESC"." $_limit";
		$proids = $model->query($sql);
		if($_REQUEST['mw']){
			echo $model->getLastSql();
			dump($proids);
		}
// 		exit;
		$proids = $this->arr2to1($proids,'id');
		return $proids;
	}
	
	/**
	 * 返回标签下的文章
	 * @param array|int $_ids
	 * @param int|string $_uid
	 * @return array:$artids
	 */
	function tagtoart($_ids,$_status = false){
		is_array($_ids) ? $where = "ob.tags_id IN (".implode(',',$_ids).")" : $where = "ob.tags_id=".$_ids;
		$_status ? $where .= " AND a.`status`=1" : "";
		$model = M();
		$sql = "SELECT ob.obj_id id FROM `tags_obj` ob LEFT JOIN article a ON ob.obj_id=a.id WHERE $where  ORDER BY ob.sequence DESC";
		$temp = $model->query($sql);
// 		echo $model->getLastSql();
// 		dump($temp);
// 		$model = M('Article');
// 		$where['tags_id'] = is_array($_ids) ? array('IN',implode(',', $_ids)) : $_ids;
// 		$ids = $this->tags_obj->field('obj_id')->where($where)->order('sequence DESC')->select();
// 		$ids = $this->arr2to1($ids,'obj_id');
// 		$map = array();
// 		$map['user_id'] = $_uid;
// 		$_status ? $map['status'] = $_status : false;
// 		$temp = $model->field('id')->where($map)->select();
		$artids = $this->arr2to1($temp,'id');
		return $artids;
	}
	
	/**
	 * 返回页面某个或某些位置上的标签
	 * 或内容
	 * @param string $_uid
	 * @param array|string $_postion
	 * @param bloom $_content 是否输出标签内容
	 * @return $taginfo
	 */
	function postotags($_uid,$_postion,$_content = false) {
		$where['user_id'] = $_uid; 
		$where['layout'] = $_postion;
		$where['status'] = 1;
 		
		$time=time();
		$res = $this->layout->field('cell_id,type')->where($where)->order('sequence desc')->select();
		$taginfo = array();
		if($_content){
			foreach ($res as $k => $v){
				$taginfo[$v['cell_id']] = $this->_tags($v['cell_id']);
			}
		}else {
			$layout_info = array();	
			foreach ($res as $vo){
				$map['id'] = $vo['cell_id'];
				if($vo['type'] == 3){						
					$adsview = $this->ads->where($map)->find();
					$st = $adsview['starttime'];
					$et = $adsview['endtime'];
					if((!$st && $et && $et>=$time) || ($st && !$et && $st<=$time) || (!$st && !$et) ||($st && $et && $st<=$time && $et>=$time)){
						$adsview['enable'] = true;
						$layout_info['ads'][] = $adsview;					
					}
					/*
					//输出过期广告，暂时保留
					else{
						$adsview['enable'] = false;
						$layout_info['ads'][] = $adsview;					
					}*/
				}else{
					$layout_info['tags'][] = $this->tags->field('id,name')->where($map)->find();
				}
			}	
			
		}
		return $layout_info;
	}
	/**
	 * 选出显示的标签
	 */
	function get_show_tags($_uid=0){
		$key = 'index-left';
		return $this->status_tags2($_uid,$key,1);
	}
	/**
	 * 选出隐藏的标签
	 */
	function get_hide_tags($_uid=0){
		$key = 'index-left';
		return $this->status_tags2($_uid,$key,2);
	}
	/**
	 * 更新标签的显示状态   
	 */
	 function upst($arr=array()){
		foreach($arr as $v){
			$where['id'] = $v['id'];
			$where['status'] = $v['status'];
			$where['layout'] = 'index-left';
			$where['user_id'] =$_GET['cid'];
			$where['type'] =1;
			$res = $this->layout->save($where);
			if(!$res)
			  $this->layout->add($where);
		}
	}
	/**
	 * 返回页面内容
	 * @param string $_web
	 * @return array $info
	 */
	function web($_web,$_uid){
		$info = array();
		$_layout = C('layout_config');
		$cachename=md5(serialize($_layout[$_web]).$_uid);
		$info=S($cachename);
		if($_REQUEST['mw']){
			$info = array();
			echo $info;
		}
		if(empty($info)){
			foreach ($_layout[$_web] as $k => $v){
				$postion = $_web.'-'.$v;
				$info[$v] = $this->_get($postion, $_uid);
			}
			//S($cachename,$info,300);
		}
		return $info;
	}

	/** 
	 * 查询
	 * 包括获取布局、获取标签、获取标签内容
	 * @param array $map 获取条件
	 * @return array $getinfo
	 */
	function _get($_action,$_uid){
		$where['user_id'] = $_uid;
		$where['layout'] = $_action;
		$where['status'] = 1;
		$temp = $this->layout->field('cell_id,type,sequence')->where($where)->order('sequence DESC')->select();
		$layout = array();
		foreach ($temp as $k => $v){
			if($v['type'] == '1'){
				if($_action == 'index-right'){
					$layout['tags'][]= $this->_tags($v['cell_id']);
				}else{
					$layout['tags'][] = $this->tags->field('id,name,code,user_id,type')->where(array('id'=>$v['cell_id']))->order('sequence DESC')->find();
				}
			}elseif($v['type'] == '2'){
				$layout['ads'][] = $this->_ads($v['cell_id']);
			}
		}
		return $layout;
	}
	
	/**
	 * 返回标签内容
	 * @param string $_id
	 * @return array $tags
	 */
	function _tags($_id,$_limit = FALSE){
		$tags = array();
		$tags = $this->tags->field('id,name,code,user_id,type')->where('`id`='.$_id)->find();
// 		dump($tags);
// 		exit;
// 		$_limit = $_limit ? $_limit : 8;
		if($tags['type'] == '1'){
			$info = $this->tagtopro($_id, $tags['user_id'],TRUE,8);
// 			dump($info);
// 			$dao=D('PStatusPrice');
// 			$where=array();
// 			$where['tags_id']=$_id;
// 			$where['status']=1;
// 			$where['pstatus']=1;
// 			$where['user_id']=$tags['user_id'];
// 			$info = $dao->field('obj_id')->where($where)->group('obj_id')->order('`sequence` DESC')->limit($_limit)->select();
			$tags['product'] = $info;
		}
// 		elseif($tags['type'] == "2"){
// 			$model = M();
// 			$sql = "SELECT a.id FROM `tags` as t LEFT JOIN tags_obj as o ON t.id=o.tags_id LEFT JOIN article as a ON t.user_id=a.cid AND o.obj_id=a.id WHERE t.id=$_id AND
// a.`status`=1 ORDER BY o.sequence DESC";
// 			$ids = $model->query($sql);
// 			echo $model->getLastSql();
// 			dump($ids);
// 			exit;
// 			$tags['product'] = $this->arr2to1($ids,'id');
// 		}
		return $tags;
	}
	
	/**
	 * 返回标签内容 : 广告
	 * @param unknown_type $_id
	 * @return unknown
	 */
	function _ads($_id){
		$adv = $this->ads->where(array('id'=>$_id))->order('sequence DESC')->select();
		return $adv;
	}
	
	/**
	 * 根据标签返回广告信息
	 * @param int|string $_id
	 * @return array $adsinfo
	 */
	function tagtoads($_id){
		$model = M();
		$sql = "SELECT * FROM `layout` as l LEFT JOIN ads as a ON l.cell_id=a.id WHERE l.id=".$_id;
		$adsinfo = $model->query($sql);
		return $adsinfo;
	}
	
	/**
	 * 二维数组返回一维或字符串
	 * @param array $_arr
	 * @param string $_field
	 * @param string $_type 1为数组 2为字符串
	 * @return multitype:array|multitype:string
	 */
	function arr2to1($_arr,$_field = 'id',$_type = '1'){
		if ( ! $_arr ) return array();
		$arrayids = array();
		foreach ($_arr as $k => $v){
			$arrayids[$k] = $v[$_field];
		}
		if($_type != '1') $arrayids = implode(',',$arrayids);
		
		return $arrayids;
	}
	
}